package org.hzz.caffeine.runner;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.hzz.caffeine.db.UserRepository;
import org.hzz.caffeine.entity.User;
import org.hzz.common.utils.FastJsonUtil;

import java.time.Duration;
import java.util.concurrent.ConcurrentMap;

/**
 * @author 胖卡
 * @version 1.0.0
 * @date 2024/7/14
 */
@Slf4j
public class CacheAsMapMain {
    public static void main(String[] args) {
        // 返回的是一个LoadingCache类型
        LoadingCache<Integer, User> userLoadingCache = Caffeine.newBuilder()
                .maximumSize(100)
                .expireAfterAccess(Duration.ofSeconds(1)) //
                .expireAfterWrite(Duration.ofSeconds(1)) // 设置成1s过期
                .build(UserRepository::getById);

        ConcurrentMap<Integer, User> map = userLoadingCache.asMap();
        log.info(FastJsonUtil.toJSONStr(map));

        // 现在我们没有放东西，直接获取
        userLoadingCache.get(1);
        userLoadingCache.get(2);

        log.info(FastJsonUtil.toJSONStr(map));

        // 又加入一个新的数据
        userLoadingCache.get(3);
        log.info(FastJsonUtil.toJSONStr(map));
        log.info("{}",map == userLoadingCache.asMap());
    }
}
